package cn.xrj.demo.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class PermutationAndCombination {
    public static void main(String[] args) {
        //可自定义数组长度，可改成变量
        String[] data = {"a", "b", "c", "d", "e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
        //自定义选择其中n个元素，可改成变量
        int n = 3;
        List<List<String>> rlist = PermutationAndCombination(Arrays.asList(data), n);
        for (List<String> list : rlist) {
            System.out.println(list);
        }
        System.out.printf("排列总和:"+rlist.size());
    }

    /**
     * @param data：需要排列的原始集合
     * @param n:选择元素的个数，如选择3个的所有全排列
     * 功能:计算从集合m抽取n个不同元素（值不同，顺序不同）的所有全排列
     */
    public static List<List<String>> PermutationAndCombination(List<String> data, int n) {
        List<List<String>> rlist = new ArrayList<List<String>>();
        if (n == 1) {
            for (String s : data) {
                List<String> list = new ArrayList<String>();
                list.add(s);
                rlist.add(list);
            }
            return rlist;
        }


        for (int i=0; i<data.size(); i++) {
            List<String> list = new ArrayList<String>(data);
            list.remove(i);
            List<List<String>> sub = PermutationAndCombination(list, n-1);
            for (List<String> slist : sub) {
                slist.add(0, data.get(i));
                rlist.add(slist);
            }
        }
        return rlist;
    }
}
